package com.jerome.rmi.test;

import com.jerome.rmi.Calculator;
import com.jerome.rmi.enums.OperatorEnum;

import java.util.List;

/**
 * @author jerome
 * @date 2023/7/29
 */
class ClientRunnable implements Runnable {
    private Thread t;
    /**
     * threadName
     */
    private String threadName;
    /**
     * remoteService
     */
    private Calculator remoteService;
    /**
     * datasource
     */
    private List<Integer> nums;

    public ClientRunnable(String threadName, Calculator remoteService,List<Integer> nums) {
        this.threadName = threadName;
        this.remoteService = remoteService;
        this.nums = nums;
    }

    public void run() {
        try {
            String threadNameStr = "threadName:"+threadName+",";
            System.out.println(threadNameStr+",nums:"+nums);
            for (Integer num : nums) {
                remoteService.pushValue(num);
            }
            remoteService.pushOperation(OperatorEnum.MIN.getName());
            System.out.println(threadNameStr+"min:"+remoteService.pop());
            System.out.println(threadNameStr+"-----------------------------");
            for (Integer num : nums) {
                remoteService.pushValue(num);
            }
            remoteService.pushOperation(OperatorEnum.MAX.getName());
            System.out.println(threadNameStr+"max:"+remoteService.pop());
            System.out.println(threadNameStr+"-----------------------------");
            for (Integer num : nums) {
                remoteService.pushValue(num);
            }
            remoteService.pushOperation(OperatorEnum.LCM.getName());
            System.out.println(threadNameStr+"lcm:"+remoteService.pop());
            System.out.println(threadNameStr+"-----------------------------");
            for (Integer num : nums) {
                remoteService.pushValue(num);
            }
            remoteService.pushOperation(OperatorEnum.GCD.getName());
            System.out.println(threadNameStr+"gcd:"+remoteService.pop());
            System.out.println(threadNameStr+"-----------------------------");
            for (Integer num : nums) {
                remoteService.pushValue(num);
            }
            System.out.println(threadNameStr+"pop:" + remoteService.pop());
            System.out.println(threadNameStr+"delay start:" + System.currentTimeMillis());
            System.out.println(threadNameStr+"delayPop:" + remoteService.delayPop(5000));
            System.out.println(threadNameStr+"delay end:" + System.currentTimeMillis());
            System.out.println(threadNameStr+"pop:" + remoteService.pop());
        } catch (Exception e) {
            System.err.println("RMI client exception: " + e.toString());
        }
    }

    public void start () {
        if (t == null) {
            t = new Thread (this, threadName);
            t.start ();
        }
    }
}
